package fr.univ.colloque.dao;

import fr.univ.colloque.data.Institution;
import fr.univ.colloque.util.PoolConnexion;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class InstitutionDao
{
    /**
     * Retourne l'institution correspondant à l'identifiant passé en paramètre
     * 
     * @param id identifiant de l'institution souhauté
     * @return institution souhaité ou null si non trouvé
     */
    public Institution get(int id)
    {
        Institution instit = null;
        
        PoolConnexion pool = PoolConnexion.getInstance();
        
        String requete = "select * from INSTITUTION where id_instit=?";
        PreparedStatement pStat = null;
        
        Connection con = null;
        ResultSet rs = null;
           
        try
        {
            con = pool.getConnexion();
            pStat = con.prepareStatement(requete);
            pStat.setInt(1, id);
            rs = pStat.executeQuery();
            
            if ( rs.next() )
            {
                instit = new Institution();
                instit.setId(id);
                instit.setLibelle(rs.getString("libelle_instit"));
            }
        }
        catch (SQLException ex)
        {
            Logger.getLogger(PersonneDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally
        {
            pool.fermerConnexion(rs, pStat, con);
        }
        return instit;
    }
    
    /**
     * retourne la liste de toutes les institutions
     * 
     * @return 
     */
    public List<Institution> getListeInstitutions()
    {
        List<Institution> lstInst;
        lstInst = new ArrayList<Institution>();
        PoolConnexion pool = PoolConnexion.getInstance();

        String requete = "select * from INSTITUTION";
        PreparedStatement pStat = null;

        Connection con = null;
        ResultSet rs = null;

        try
        {
            con = pool.getConnexion();
            pStat = con.prepareStatement(requete);
            rs = pStat.executeQuery();

            while (rs.next())
            {
                Institution instit;
                instit = new Institution();
                instit.setId(rs.getInt("id_instit"));
                instit.setLibelle(rs.getString("libelle_instit"));
                lstInst.add(instit);
            }
        }
        catch (SQLException ex)
        {
            Logger.getLogger(PersonneDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally
        {
            pool.fermerConnexion(rs, pStat, con);
        }
        return lstInst;
    }
}
